<?php

namespace yunj\library\mailer;

class Mailer {

    /**
     * 配置
     * @var array
     */
    protected $config = [
        'mailer' => 'smtp',         // 使用服务
        'host' => 'smtp.163.com',   // 发送服务的SMTP服务器地址
        'port' => 465,              // 发送服务的SMTP服务器端口
        'encryption' => 'ssl',      // 发送服务的SMTP加密模式
        'username' => '',           // 发送服务的邮箱
        'password' => '',           // 发送服务的邮箱授权密码
        'from_address' => '',       // 发件人邮箱
        'from_name' => '',          // 发件人名称
    ];

    /**
     * @var \Swift_Mailer
     */
    protected $mailer;

    /**
     * 附件
     * @var \Swift_Attachment
     */
    protected $attachment;

    /**
     * @param array $config
     * @return $this
     */
    public function setConfig(array $config) {
        $this->config = $config + $this->config;
        return $this;
    }

    /**
     * @param \Swift_Mailer $mailer
     */
    protected function setMailer(): void {
        $config = $this->config;
        // mailer
        $transport = new \Swift_SmtpTransport($config['host'], $config['port'], $config['encryption']);
        $transport->setUsername($config['username'])->setPassword($config['password']);
        $this->mailer = new \Swift_Mailer($transport);
    }

    public function __construct(array $config = []) {
        $this->setConfig($config);
        $this->setMailer($config);
    }

    /**
     * 附件
     * @param string $filePath  文件地址
     * @param string $fileName  文件名称
     * @return $this
     */
    public function attach(string $filePath, string $fileName = '') {
        if (!$fileName) {
            if (!strstr($filePath, '/')) $fileName = $filePath;
            $fileName = substr($filePath, strripos($filePath, '/') + 1);
        }
        $this->attachment = \Swift_Attachment::fromPath($filePath)->setFilename($fileName);
        return $this;
    }

    /**
     * 发送
     * @param array|string $to 收件地址
     * @param string $subject
     * @param string $body
     * @return int  成功收件人的数量。为0，表示失败
     */
    public function send($to, string $subject, string $body): int {
        $message = new \Swift_Message();
        $message->setFrom($this->config['from_address'], $this->config['from_name']);
        $to = is_array($to) ? $to : [$to];
        foreach ($to as $v) {
            if (!filter_var($v, FILTER_VALIDATE_EMAIL)) throw new \RuntimeException('邮箱地址[' . $v . ']异常');
        }
        $message->setTo($to)->setSubject($subject)->addPart($body, 'text/html', 'utf8');
        // 附件
        if ($this->attachment) $message->attach($this->attachment);
        // 发送
        return $this->mailer->send($message);
    }

}